from helpFunc import *
import socket,select,os,time
from connbase import *


class tcpRePeer(tcpReBase):
    def __init__(self):
        tcpReBase.__init__(self)     
        self.connectPollingMap = {}
        self.ssPort = 8080        
        s = socket.socket()
        add = ('0.0.0.0',server_port)
        s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        s.bind(add)
        s.listen(1)
        self.connSock,b = s.accept()
        print (b)
        self.connSock.setblocking(False)
        while True:
            self.dowork()
            
    def dowork(self):       
        self.doPeriod()
        rl = [self.connSock]
        if len(self.peerBuf)<con_connBufSize:
            rl += self.getReadSocks()

        wl = self.getWriteSocks()+list(self.connectPollingMap.keys())
        if self.peerBuf :
            wl.append(self.connSock)

        el = self.connectPollingMap.keys()
        rl,wl,el = select.select(rl,wl,el,1)

        for sock in rl:
            if sock == self.connSock:
                ss = sock.recv(tcpReadLen)    
                self.recvLen += len(ss)
                msgList = self.dealData( ss)
                for one in msgList:
                    ty,id,da = self.decodeMsg(one)                                     
                    if  ty==ping_g:
                        print ('ping')
                        dd = self.makeMsg(ping_g,id,b'\x00')                          
                        self.sendMsg(dd)                          
                    if  ty==askConn_g:
                        print ('ask conn')
                        if self.connNum > self.maxNum:
                            print ('too much',self.connNum)
                            dd = self.makeMsg(connBack_g,id,b'\x00')                          
                            self.sendMsg(dd)                              
                        try:
                            s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)                                                                                             
                            s.setblocking(0)
                            s.connect_ex(('127.0.0.1',self.ssPort))
                            self.connectPollingMap[s]={'id':id}
                        except Exception as e:
                            print (e)
                            s.close()
                            dd = self.makeMsg(connBack_g,id,b'\x00')    
                            self.sendMsg(dd)    
                    else:
                        self.dealConnsockNormal(id, ty,da)
                continue
            self.dealProxysocks(sock)
        for sock in wl:
            if sock == self.connSock:
                n = self.connSock.send(self.peerBuf)
                self.sendLen += n
                self.peerBuf = self.peerBuf[n:]
                continue            
            if sock in self.connectPollingMap:
                id = self.connectPollingMap[sock]['id']
                del self.connectPollingMap[sock]
                dd = self.makeMsg(connBack_g,id,b'\x01')    
                self.sendMsg(dd)
                self.proxySocks[sock] = {'id':id,'data':b'','peerclose':False,'peerFull':False,'tellMyFull':False}
                self.idMap[id] = {'sock':sock}
                self.connNum +=1 
                print ('accept',self.connNum )
                continue
            self.dealWritesocks(sock)

        for sock in el:
            if sock in self.connectPollingMap:
                sock.close()
                id = self.connectPollingMap[sock]['id']
                del self.connectPollingMap[sock]                
                dd = self.makeMsg(connBack_g,id,b'\x00')      
                self.sendMsg(dd)                     

if __name__ == '__main__':
    tcpRePeer()
